#include"threadpool.h"
#include<sys/signal.h>

threadpool* create_threadpool(u_int32_t max_thread_num){
    threadpool* this=(threadpool*)calloc(1,sizeof(threadpool));
    this->threads=(pthread_t*)calloc(max_thread_num,sizeof(pthread_t));
    this->bq=create_blockingqueue();
    this->max_thread_num=max_thread_num;
    this->live_thread_num=0;
    this->busy_thread_num=0;
    this->is_shutdown=0;
    return this;
}

//或者在函数里自己delete参数data，然后把他们都放在worker里
void* run(void* w){
    worker* wk=(worker*)w;
    threadpool* this=wk->pool;
    while(!this->is_shutdown){
        if(wk!=NULL){
            wk->work(wk->data);
            wk=NULL;
        }else{
            wk=bq_ub_poll(this->bq,3);
            if(wk==NULL){
                printf("poll NULL!\n");
            }
        }
    }
    return NULL;
}

void execute_threadpol(worker* w){
    threadpool* this=w->pool;
    if(this->live_thread_num<this->max_thread_num){
        pthread_t tid;
        pthread_create(&tid,NULL,run,(void*)w);
        u_int32_t index=this->live_thread_num++;
        this->threads[index]=tid;
        //for test
        printf("new thread!\n");
    }else{
        bq_push(this->bq,(void* )w);
        //for test
        printf("in queue!\n");
    }
}

void shutdown_threadpool(threadpool*this){
    this->is_shutdown=1;
    for(int i=0;i<this->live_thread_num;i++){
        pthread_join(this->threads[i],NULL);
    }
}

void destory_threadpool(threadpool*this){
    free(this->threads);
    destory_bk_queue(this->bq);
}
